<?php

namespace App\Models;

class Punishment extends BaseModel
{
    protected static string $table = 'punishments';

    public static function getByStudentId(int $studentId): array
    {
        $db = self::getDb();
        return $db->query(
            "SELECT * FROM `punishments` WHERE `student_id` = ? ORDER BY `date` DESC",
            [$studentId]
        );
    }

    public static function search(array $filters, int $page = 1, int $pageSize = 20): array
    {
        $db = self::getDb();
        $offset = ($page - 1) * $pageSize;
        
        $sql = "SELECT p.*, s.student_id, s.name as student_name 
                FROM `punishments` p 
                LEFT JOIN `students` s ON p.student_id = s.id 
                WHERE 1=1";
        $params = [];
        
        if (!empty($filters['studentId'])) {
            $sql .= " AND p.student_id = ?";
            $params[] = $filters['studentId'];
        }
        
        // 获取总数
        $countSql = preg_replace('/SELECT p\.\*, s\.student_id, s\.name as student_name/', 'SELECT COUNT(*) as count', $sql);
        $countResult = $db->queryOne($countSql, $params);
        $total = (int) $countResult['count'];
        
        // 获取数据
        $sql .= " ORDER BY p.created_at DESC LIMIT {$pageSize} OFFSET {$offset}";
        $list = $db->query($sql, $params);
        
        return [
            'list' => $list,
            'total' => $total
        ];
    }
}

